#!/bin/bash
#
# Podman-based mktree backend using an OCI image to build and run RPM.
# Works standalone (outside of a build directory) too.

PROGRAM=$(basename $0)
if [ "$PROGRAM" == "mktree" ]; then
    # Running from build directory
    PODMAN=@PODMAN@
    CONTEXT=@CMAKE_SOURCE_DIR@
else
    # Running from source directory
    PODMAN=$(echo $PROGRAM | cut -d'.' -f2)
    CONTEXT=..
fi

IMAGE=rpm
NAME=${IMAGE}-sandbox
ROOTLESS=$([ $(id -u) == 0 ] && echo 0 || echo 1)

CMD=$1; shift
case $CMD in
    build)
        cd $(dirname $0)
        $PODMAN build -t $IMAGE -f Dockerfile $CONTEXT
    ;;
    shell)
        if [ -n "$($PODMAN ps -a -q -f name=$NAME)" ]; then
            $PODMAN start $NAME >/dev/null
            $PODMAN attach $NAME
            exit
        fi
        $PODMAN run --privileged -it --name $NAME --hostname sandbox \
                    -e ROOTLESS=$ROOTLESS -v $PWD:/srv:z $IMAGE "$@"
        exit 0
    ;;
    check)
        # Pass select options to $PODMAN
        case "$1" in
            # Useful for CI environments without a tty
            --interactive=*) OPTS=$1; shift ;;
            *) OPTS= ;;
        esac
        $PODMAN run --privileged -it --rm --read-only --tmpfs /tmp \
                    -v /srv --workdir /srv -e ROOTLESS=$ROOTLESS \
                    $OPTS $IMAGE mktree check "$@"
    ;;
    reset)
        $PODMAN stop $NAME >/dev/null &&
        $PODMAN rm $NAME >/dev/null
    ;;
    *)
        echo "Unsupported command." >&2
        exit 1
    ;;
esac
